package com.zhx.threadcoreknowledge.background;

/**
 * @author ：zhanghaixuan
 * @date ：Created in 2019-10-05 09:58
 * 用途         ： 必然死锁的例子,第二种线程安全的问题
 */
public class MultiThreadErrorLock implements Runnable{
    int flag = 1;

    static Object lock1 = new Object();

    static Object lock2 = new Object();

    @Override
    public void run() {
        System.out.println("flag = " + flag);

        if (flag == 1) {
            synchronized (lock1){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (lock2){
                    System.out.println("1");
                }
            }
        }

        if(flag ==0){
            synchronized (lock2){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                synchronized (lock1){
                    System.out.println("0");
                }
            }
        }
    }

    public static void main(String[] args) {
        MultiThreadErrorLock multiThreadErrorLock1 = new MultiThreadErrorLock();
        MultiThreadErrorLock multiThreadErrorLock2 = new MultiThreadErrorLock();
        multiThreadErrorLock1.flag =1;
        multiThreadErrorLock2.flag = 0;
        Thread thread1 = new Thread(multiThreadErrorLock1);
        Thread thread2 = new Thread(multiThreadErrorLock2);

        thread1.start();
        thread2.start();
    }
}
